package model;

import java.awt.Graphics;
import java.awt.image.BufferedImage;

import org.apache.log4j.Logger;

import util.GameUtil;
import util.ImageUtil;

public class Tank extends Entity
{

	private TankGun gun;
	Logger logger;

	public Tank(String tankRef, String gunRef, int x, int y)
	{
		super(tankRef, x, y);
		this.gun = new TankGun(gunRef, x, y);
		logger = Logger.getLogger(this.getClass().getName());
	}

	@Override
	public void draw(Graphics g)
	{		
		if (isReversed())
		{

			BufferedImage gunSrc = this.gun.sprite.getImage();
			BufferedImage flippedImage = ImageUtil.getImageFlippedHorizontal(gunSrc);
			BufferedImage rotatedImage = ImageUtil.rotate(flippedImage, -angle);
			g.drawImage(rotatedImage, (int)x, (int) (y - 1.53 * this.sprite.getHeight()), null);

			BufferedImage bufferedImageSrc = this.sprite.getImage();
			flippedImage = ImageUtil.getImageFlippedHorizontal(bufferedImageSrc);
			g.drawImage(flippedImage, (int) x, (int) y, null);

		}
		else
		{
			//this.gun.sprite.draw(g, (int) ((x - 0.18 * this.sprite.getWidth())), (int) (y - 1.53 * this.sprite.getHeight()));
			BufferedImage bufferedImageSrc = this.gun.sprite.getImage();
			BufferedImage rotatedImage = ImageUtil.rotate(bufferedImageSrc, angle);
			g.drawImage(rotatedImage, (int) ((x - 0.18 * this.sprite.getWidth())), (int) (y - 1.53 * this.sprite.getHeight()), null);
			sprite.draw(g, (int) x, (int) y);

		}
	}

	@Override
	public void move(long delta)
	{
		
		double angleModifier = (delta * dr) / 1000;
		//logger.debug("Angle modifier: " + angleModifier + ", current angle: " + angle);
		if (angleModifier + angle < 10 && angleModifier + angle > -90)
		{			
			angle += angleModifier;
		}
		
		if ((dx < 0) && (x < 10))
		{
			return;
		}

		if ((dy < 0) && (y < 10))
		{
			return;
		}

		if ((dx > 0) && (x > GameUtil.GAME_SCREEN_WIDTH - this.sprite.getWidth()))
		{
			return;
		}

		if ((dy > 0) && (y > GameUtil.GAME_SCREEN_HEIGHT - this.sprite.getHeight()))
		{
			return;
		}

		x += (delta * dx) / 1000;
		y += (delta * dy) / 1000;		
	}

	@Override
	public void scaleImage(double factor)
	{
		Sprite spriteSrc = this.gun.sprite;
		spriteSrc.setImage(ImageUtil.getScaledImage(spriteSrc.getImage(), factor));
		super.scaleImage(factor);
	}		

	@Override
	public void collidedWith(Entity other)
	{
		if (other instanceof Tank)
		{
			// gameScreen.setCollision(true);
		}
		else
		{
			// gameScreen.setCollision(false);
		}

	}

}